package com.qf.shiroboot.shiro;

import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {


    // SecurityManager
    @Bean
    public DefaultWebSecurityManager securityManager(CustomRealm realm,RedisSessionDAO redisSessionDAO,RedisCacheManager redisCacheManager){
        //1. 创建DefaultWebSecurityManager
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //2. 绑定SecurityManager和Realm
        securityManager.setRealm(realm);

        //3. 创建DefaultWebSessionManager
        RedisWebSessionManager sessionManager = new RedisWebSessionManager();

        //4. 将RedisSessionDAO设置给DefaultWebSessionManager
        sessionManager.setSessionDAO(redisSessionDAO);

        //5. 将DefaultWebSessionManager设置给DefaultWebSecurityManager
        securityManager.setSessionManager(sessionManager);

        //6. 设置redisCacheManager
        securityManager.setCacheManager(redisCacheManager);

        //7. 返回DefaultWebSecurityManager对象
        return securityManager;
    }



    // ShiroFilterChainDefinition
    @Bean
    public DefaultShiroFilterChainDefinition shiroFilterChainDefinition(){
        //1. 创建DefaultShiroFilterChainDefinition对象
        DefaultShiroFilterChainDefinition shiroFilterChainDefinition = new DefaultShiroFilterChainDefinition();

        //2. 创建LinkedHashMap
        LinkedHashMap<String,String> filterChain = new LinkedHashMap<>();

        //3. 设置过滤器链信息
        filterChain.put("/favicon.ico","anon");         //  放行
        filterChain.put("/login","anon");               //  放行
        filterChain.put("/doLogin","anon");             //  放行

        filterChain.put("/roles","roles[街溜子,华子]"); // 角色校验
        filterChain.put("/perms","perms[user:walk]"); // 权限校验

        filterChain.put("/**","authc");                 //  认证后才可以进入.

        //4. 设置到shiroFilterChainDefinition对象中
        shiroFilterChainDefinition.addPathDefinitions(filterChain);

        //5. 返回DefaultShiroFilterChainDefinition对象
        return shiroFilterChainDefinition;
    }

}
